package fun.boomcat.luckyhe.mirai.plugin.bilibilivideoinfoautogenerator.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class URLUtil {
    private static String dataPath;

    public static void init(String dp) {
        dataPath = dp;
    }

    public static String getDownloadPicPath(String picUrl) throws IOException {
        URL url = new URL(picUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setConnectTimeout(5000);
        httpURLConnection.setReadTimeout(5000);

        String[] picFileUrlSplit = picUrl.split("/");
        String filename = picFileUrlSplit[picFileUrlSplit.length - 1];
        String filepath = dataPath + "/" + filename;

        writeFileStream(new DataInputStream(httpURLConnection.getInputStream()), filepath);

        return filepath;
    }

    private static void writeFileStream(InputStream is, String filepath) throws IOException {
        File file = new File(filepath);
        file.getParentFile().mkdirs();
        FileOutputStream fos = new FileOutputStream(file);
        byte[] buf = new byte[1024];
        int len;
        while ((len = is.read(buf)) > 0) {
            fos.write(buf, 0, len);
        }
        is.close();
        fos.close();
    }


}
